package com.zhongshengnetwork.rightbe.wzt.view;

import android.content.Intent;
import android.os.Bundle;
//import android.support.annotation.NonNull;
//import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WZTLikeFragment extends BaseAnalyticsFragment {

    private long id;
    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    private List<CircleLangModel> list;
    private RecyclerView listview;
    private WZTUserRecyclerAdapter adapter;
    private View rootView;//缓存Fragment view

    //private NestedScrollView wzt_nestedScrollView_layout;

    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;

    public static WZTLikeFragment newInstance(long id) {
        WZTLikeFragment wztLikeFragment = new WZTLikeFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("id", id);
        wztLikeFragment.setArguments(bundle);
        return wztLikeFragment;
    }

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            id = args.getLong("id");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.wzt_viewpaper_layout, container, false);
            avi = (AVLoadingIndicatorView) rootView.findViewById(R.id.avi);
            pageindex = 0;
            if (list == null) {
                list = new ArrayList<CircleLangModel>();
            }

            listview = (RecyclerView) rootView.findViewById(R.id.wzt_listview);

            adapter = new WZTUserRecyclerAdapter(getActivity(), list);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            listview.setLayoutManager(layoutManager);
            listview.setHasFixedSize(false);
            listview.setNestedScrollingEnabled(false);
            ((DefaultItemAnimator) listview.getItemAnimator()).setSupportsChangeAnimations(false);//解决局部更新闪烁问题
            listview.setAdapter(adapter);
            /*
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Log.e("TAG", "position=" + position);
                    if (list == null || list.size() == 0) {
                        return;
                    }
                    int index = position;// - 1;
                    while (index < 0) {//解决部分手机点击第一条不是从1开始的问题
                        index += 1;
                    }
                    CircleLangModel model = list.get(index);
                    Intent intent = new Intent(getActivity(), UserLangActivity.class);
                    intent.putExtra(APIKey.useridKey,model.getUserid());
                    intent.putExtra(APIKey.typeKey,1);
                    intent.putExtra(APIKey.titleKey,model.getNickname());
                    startActivity(intent);
                }
            });
            */

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(false);//禁用刷新
            mRefreshLayout.setEnableLoadMore(false);//启用加载
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    getData();
                }
            });

            LinearLayout wzt_user_layout = (LinearLayout) rootView.findViewById(R.id.wzt_user_layout);
            wzt_user_layout.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    private void getData() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("dataId", id + "");
                map.put("pageIndex", pageindex + "");
                map.put("pageRecord", Records + "");
                HttpsUtils.miniAppDo(map, "weishu/theme/like/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                    if (commonModel.getFlag().equals("1")) {
                                        List<CircleLangModel> l = GsonTools.getCircleLangModel(data);
                                        if (l != null && l.size() > 0) {
                                            if (l.size() >= Records) {
                                                //listview.setPullLoadEnable(true);
                                                mRefreshLayout.setEnableLoadMore(true);
                                            } else {
                                                //listview.setPullLoadEnable(false);
                                                mRefreshLayout.setEnableLoadMore(false);
                                            }
                                            if (pageindex == 0){
                                                list.clear();
                                            }
                                            list.addAll(l);
                                        } else {
                                            isHasMore = false;
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        adapter.notifyDataSetChanged();
                                        if (l != null && l.size() > 0){
                                            pageindex += 1;
                                        }
                                    } else {
                                        CustomApplication.showTip(commonModel, getActivity());
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                }
                            });
                        }
                    }
                });
            }
        }).start();

    }

}
